// import 'package:dio/dio.dart' as prefix0;
import 'package:flutter/material.dart';
import 'package:wanchong/api/user.dart';
import 'package:wanchong/app/app.dart';
import 'package:wanchong/bean/login_entity.dart';
import 'package:wanchong/intent/login.dart';
import 'package:wanchong/path.dart';
import 'package:wanchong/utils/common.dart';
import 'package:wanchong/utils/http.dart';
import 'package:wanchong/widget/app_bar.dart';
import 'package:wanchong/widget/custom_password.dart';
import 'package:wanchong/widget/keyboard.dart';
import 'package:wanchong/widget/password.dart';
import 'package:wanchong/bean/send_sms_response_entity.dart';
import 'dart:async';

class Check extends StatefulWidget {
  @override
  _CheckState createState() => _CheckState();
}

class _CheckState extends State<Check> {
  PhoneObj _phoneObj;
  bool loading = false;
  var oneSec = const Duration(seconds: 1);
  Timer _timer;
  int timer = 0;
  String pwdData = '';
  bool countDown = false;
  VoidCallback _showBottomSheetCallback;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  void initState() {
    super.initState();
    _showBottomSheetCallback = _showBottomSheet;
    print("Check init");
  }

  @override
  Widget build(BuildContext context) {
    _phoneObj = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      key: _scaffoldKey,
      resizeToAvoidBottomPadding: false,
      appBar: MyAppBar(
        color: Colors.transparent,
        child: Align(
          alignment: Alignment.centerLeft,
          child: GestureDetector(
            onTap: () {
              // print("密码登录");
              ///返回上一页
              Navigator.of(context).popAndPushNamed(_phoneObj.getPhone());
            },
            child: Container(
              padding: const EdgeInsets.all(8.0),
              margin: const EdgeInsets.only(left: 7.0),
              child: Image.asset("assets/login/top_return_icon.png"),
            ),
          ),
        ),
      ),
      body: Container(
          margin: const EdgeInsets.only(left: 46.0, right: 46.0),
          child: Column(
            children: <Widget>[
              SizedBox(
                height: 37.0,
              ),
              Container(
                width: double.infinity,
                child: Text(
                  "输入验证码",
                  style: TextStyle(
                      fontSize: 28.0,
                      color: Color(0xFF3C4450),
                      fontWeight: FontWeight.w700),
                ),
              ),
              Container(
                width: double.infinity,
                child: Text(
                  "验证码已送至 +86 " + _phoneObj.getPhone(),
                  style: TextStyle(color: Color(0xFF647280), fontSize: 14.0),
                ),
              ),
              SizedBox(
                height: 50.0,
              ),
              _buildPwd(pwdData),
              SizedBox(
                height: 40.0,
              ),
              GestureDetector(
                onTap: () {
                  ///进入主页面
                  ///
                  _startMain();
                },
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(25.0),
                  child: Container(
                    alignment: Alignment.center,
                    child: Text(
                      "确认",
                      style:
                          TextStyle(color: Color(0xFFFFFFFF), fontSize: 18.0),
                    ),
                    color: pwdData.length == 4 && countDown == false
                        ? Color(0xFFFFCC33)
                        : Color(0xFFFFE599),
                    height: 50.0,
                  ),
                ),
              ),
              SizedBox(
                height: 30.0,
              ),
              GestureDetector(
                onTap: () {
                  ///判断是否已经点击
                  if (timer == 0) {
                    ///点击短信倒计时
                    ///
                    setState(() {
                      timer = 60;
                      countDown = true;
                    }); 
                    _countDown();
                    getSms();
                  }
                },
                child: Container(
                  alignment: Alignment.center,
                  child: Text(
                    "重新获取验证码" +
                        (timer == 0 ? "" : "(" + timer.toString() + ")"),
                    style: TextStyle(color: Color(0xFFFFCC33), fontSize: 12.0),
                  ),
                ),
              )
            ],
          )),
    );
  }

  Widget _buildPwd(pwdData) {
    return GestureDetector(
      child: Container(
        width: double.infinity,
        height: 40.0,
        child: CustomPassword(pwdData),
      ),
      onTap: () {
        _showBottomSheetCallback();
      },
    );
  }

  /// 底部弹出 自定义键盘  下滑消失
  void _showBottomSheet() {
    setState(() {
      // disable the button
      _showBottomSheetCallback = null;
    });
    _scaffoldKey.currentState
        .showBottomSheet<void>((BuildContext context) {
          return new MyKeyboard(_onKeyDown);
        })
        .closed
        .whenComplete(() {
          if (mounted) {
            setState(() {
              // re-enable the button
              _showBottomSheetCallback = _showBottomSheet;
            });
          }
        });
  }

  void _onKeyDown(KeyEvent data) {
    if (data.isDelete()) {
      if (pwdData.length > 0) {
        pwdData = pwdData.substring(0, pwdData.length - 1);
        setState(() {});
      }
    } else if (data.isCommit()) {
//       if (pwdData.length != 6) {
// //        Fluttertoast.showToast(msg: "密码不足6位，请重试", gravity: ToastGravity.CENTER);
//         return;
//       }
      onAffirmButton();
    } else {
      if (pwdData.length < 4) {
        pwdData += data.key;
      }
      setState(() {});
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _timer ?.cancel();
    super.dispose();
  }

  /// 密码键盘 确认按钮 事件
  void onAffirmButton() {}

  void _countDown() {
    var callback = (_timer) => {
          setState(() {
            if (timer < 1) {
              countDown = false;
              _timer.cancel();
              _timer = null;
            } else {
              timer = timer - 1;
            }
          })
        };
    _timer = Timer.periodic(oneSec, callback);
  }

  void _startMain() {
    // print(loading && pwdData.length != 4 && !countDown);
    if (loading && pwdData.length != 4 && !countDown) {
      return;
    }
    loading = true;
    smsLogin(pwdData.toString(), _phoneObj.getPhone())
        .listen((LoginEntity data) async {
      loading = false;
      await setToken("Bearer " + data.data.token);
      await setIm(data.data.im, data.data.sig);
      await dimLogin(data.data.im, data.data.sig);
      imUserSelf = ImUser(nick: data.data.im,sig: data.data.sig);
      ///登录聊天系统
      // if (_phoneObj.getPhone()=="16609447987"){
      //   await dimLogin("yyang","eJxlz8Fqg0AQgOG7TyFeLWVdsxoDPUSTJtoWMSbQ5iKLTmRdujHrGmNK373UBCp0rt8-DPOl6bpubF-TR5rnx1aoTPU1GPpMN5Dx8Id1zYqMqsyWxT*ES80kZPSgQA5oEUIwQuOGFSAUO7B70fdUlCNuCp4NN277E4QwRlNsjRNWDvi23AVhsnghZtruJRXzahV1vI1wZbqWaPv9yT5BXmyTxN-Q54p3XVj6HD7izdxslk64trvg6kT*JQbXe1*b7mJ6nqQxC2CV7zh-Gp1U7BPuDzmYuK7teSM9g2zYUQwBRhaxsI1*x9C*tR8sI10B");
      // }
      // else {
      //   await dimLogin("zw","eJxlz1FPgzAQwPF3PkXT1xk5ykqZiQ8MJY65LWxooi*ElIKdyrAUx2b87ma4xCbe6*9-udyXhRDC6f3mMud819U604dGYHSFMOCLP2waWWS5zlxV-EPRN1KJLC*1UAM6lFICYDayELWWpTwXx71hbfGaDQd*l8cAhIBPHDOR1YCL24dwloQv8cdNR0f*aiWeI3fSpI90Xtrb7ql9m-rA10nkzdW43oS8mlVBmbQxWy7iLs33AZ*AfReEbNvLpQv50bfjuHejno-kNLg2Tmr5Ls7feIQyxjzP0E*hWrmrh4CAQx3iwmmw9W39ABRwWnA_");
      // }
      ///根据返回的type判断是否需要设置密码1是不需要设置
      if (data.data.type == 1) {
        Navigator.pushNamedAndRemoveUntil(
            context, HomePath, (Route<dynamic> route) => false);
      } else {
        Navigator.pushNamedAndRemoveUntil(
            context, SetPwdPath, (Route<dynamic> route) => false);
      }
    }).onError((e) {
      loading = false;
      MyError err = e;
      alert(err.message);
    });
  }

  void getSms() {
    sendSms(_phoneObj.getPhone()).listen((SendSmsResponseEntity data) {
      loading = false;
      if (data.code == 200) {
        alert("短信发送成功");
      }
      // print(data);
    }).onError(( err) {
      MyError e = err;
      var msg = "";
      if (e.code == 300) {
        msg = e.message;
      }else{
        msg = "发送失败，请重试";
      }
      // print(err);
      alert(msg);
    });
  }

}
